#!/bin/bash
#sh noti_new_package.sh -appInfoF ${Environment_FILE_PATH} -ll "${LongLog}" -np $NotificatePeople --log-robottype "error"
#sh noti_new_package.sh -appInfoF "../example_packing_info/app_info.json" -ll "cos地址：https://a/b/123.txt\n官网：https://www.pgyer.com/lkproapp。\n更新内容：\n更新说明略\n分支信息:\ndev_fix:功能修复" -np all --log-robottype "error"


# shell 参数具名化
show_usage="args: [-appInfoF, -ll, -lt, -np]\
                                  [--app-info-json-file=, --long-log=, --log-robottype=, --notificate-forPeople=]"
                                  
while [ -n "$1" ]
do
        case "$1" in
                -appInfoF|--app-info-json-file) Environment_FILE_PATH=$2; shift 2;;
                -ll|--long-log) LongLog=$2; shift 2;;
                -lt|--log-robottype) LogRobotype=$2; shift 2;; # result / error / other
                -np|--notificate-forPeople) NotificatePeople=$2; shift 2;;
                -ignoreHeader|--ignore-verion-header) IGNORE_VERSION_HEADER=$2; shift 2;; # 不使用版本头(一般只有当出现多个截断发送的时候，才会使用)
                -enableMD|--enableMarkdown) EnableMarkdown=$2; shift 2;; # 如果允许markdown的时候，才去获取类型，不然类型传空，及默认使用text格式发送（因为markdown无法@人）
                -verbose|--verbose) verbose=$2; shift 2;;
                --) break ;;
                *) echo $1,$2,$show_usage; break ;;
        esac
done

exit_script() { # 退出脚本的方法，省去当某个步骤失败后，还去继续多余的执行其他操作
    exit 1
}

# 定义颜色常量
NC='\033[0m' # No Color
RED='\033[31m'
GREEN='\033[32m'
YELLOW='\033[33m'
BLUE='\033[34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'

if [ -z "${verbose}" ]; then
    verbose=false
fi

# 当前【shell脚本】的工作目录
# $PWD代表获取当前路径，当cd后，$PWD也会跟着更新到新的cd路径。这个和在终端操作是一样的道理的
CurrentDIR_Script_Absolute="$( cd "$( dirname "$0" )" && pwd )"
#echo "CurrentDIR_Script_Absolute=${CurrentDIR_Script_Absolute}"
#bulidScriptCommon_dir_Absolute=${CurrentDIR_Script_Absolute}/..
# bulidScriptCommon_dir_Absolute=${CurrentDIR_Script_Absolute%/*} # 使用此方法可以避免路径上有..
bulidScriptCommon_dir_Absolute=${CurrentDIR_Script_Absolute}
#echo "bulidScriptCommon_dir_Absolute=${bulidScriptCommon_dir_Absolute}"

qscript_path_get_filepath="${bulidScriptCommon_dir_Absolute}/qscript_path_get.sh"
qbase_json_file_check_script_path="$(sh ${qscript_path_get_filepath} qbase json_file_check)"
qbase_notification2wechat_path="$(sh ${qscript_path_get_filepath} qbase notification2wechat)"

echo "\n"
if [ ! -f "${Environment_FILE_PATH}" ];then
    echo "$0 ❌:您的${Environment_FILE_PATH}文件不存在，请检查！"
    exit_script
fi


if [ "${EnableMarkdown}" == "true" ]; then # 如果允许markdown的时候，才去获取类型，不然类型传空，及默认使用text格式发送（因为markdown无法@人）
    NotificationMESSAGETYPE=$(cat $Environment_FILE_PATH | jq -r '.package_noti_msgtype')
fi


#echo "\n\n\n准备发送通知......"
#echo "LongLog=${LongLog}"
#echo "NotificatePeople=${NotificatePeople}"
echo "LogRobotype_old=${LogRobotype}"
#if [ -n "${LongLog}" ]; then # 当字符串 str1 的长度大于 0（非空）时为真
if [ -z "${LogRobotype}" ] || [ "${LogRobotype}" == "null" ]; then
    LogRobotype='other'
fi
echo "LogRobotype_new=${LogRobotype}"

JQ_EXEC=`which jq`


if [ -z "${NotificatePeople}" ]; then
    NotificatePeople=$(cat ${Environment_FILE_PATH} | ${JQ_EXEC} ".package_noti_people" | sed 's/\"//g')
fi

if [ "${LogRobotype}" == "error" ]; then
    LogColor=${RED}
else
    LogColor=${GREEN}
fi
#echo "NotificatePeople=${NotificatePeople}"
if [ "${NotificatePeople}" == "null" ] || [ "${NotificatePeople}" == "none" ] ; then
    if [ -n "${LongLog}" ]; then
        if [ "${LogRobotype}" == "error" ]; then
            printf "${LogColor}发生错误了:${LongLog}${NC}" # 不发送通知的时候，有错误要记得打印出来，不然外界看不到问题
        else
            printf "${LogColor}${LongLog}${NC}" # 不发送通知的时候，有错误要记得打印出来，不然外界看不到问题
        fi
        printf "${BLUE}(温馨提示：由于您在 ${YELLOW}${Environment_FILE_PATH} ${BLUE}文件中 ${YELLOW}package_noti_people ${BLUE}的取值NotificatePeople为 ${YELLOW}${NotificatePeople} ${BLUE}，其属于 null/none 中的一种，所以不发送到企业微信或者钉钉了。${BLUE}(如需发送通知，请将 ${YELLOW}package_noti_people ${BLUE}设置为其他值))${NC}\n"
    fi
    exit
fi


sh ${qbase_json_file_check_script_path} -checkedJsonF "${Environment_FILE_PATH}"


source ${bulidScriptCommon_dir_Absolute}/a_source_env.sh -appInfoF ${Environment_FILE_PATH}


# 获取版本头(一般当出现一个长串文字被多个截断发送的时候，会使用)
function getVersionHeader() {
    PackageTargetNetworkDes=$(cat ${Environment_FILE_PATH} | ${JQ_EXEC} '.package_des.chinese' | sed 's/\"//g')
    #echo "==============PackageTargetNetworkDes=${PackageTargetNetworkDes}"


    NotificationHeaderRestult+=${NotificationEmoji}

    PackageManualInputChangeLog=$(cat ${Environment_FILE_PATH} | ${JQ_EXEC} -r '.package_update_des') # -r 去除字符串引号
    PackageErrorCode=$(cat ${Environment_FILE_PATH} | ${JQ_EXEC} -r '.package_code') # -r 去除字符串引号
    PackageErrorMessage=$(cat ${Environment_FILE_PATH} | ${JQ_EXEC} -r '.package_message') # -r 去除字符串引号
    echo "PackageManualInputChangeLog=${PackageManualInputChangeLog}"
    echo "PackageErrorCode=${PackageErrorCode}"
    echo "PackageErrorMessage=${PackageErrorMessage}"


    NewPackageVersionDes=$(cat ${Environment_FILE_PATH} | ${JQ_EXEC} '.package_des.english' | sed 's/\"//g')
    PackingState=$(cat ${Environment_FILE_PATH} | ${JQ_EXEC} -r '.packing_state') # -r 去除字符串引号
    if [ "${PackingState}" == "pack and upload finished" ] ; then
        FullPackageVersionDes="${PackageTargetNetworkDes}\n${NewPackageVersionDes}"
    else
        FullPackageVersionDes="${PackageTargetNetworkDes}:${NewPackageVersionDes}"
    fi


    if [ "${PackingState}" == "pack and upload finished" ] ; then
        if [ "${PackageErrorCode}" == "package_code_0" ] ; then
            NotificationHeaderRestult+="恭喜✅：${FullPackageVersionDes}成功。"
            
        else
            NotificationHeaderRestult+="就差上传了💪🏻：${FullPackageVersionDes}。"
        fi
    else
        # 还没到上传,脚本就因为失败而结束执行了
        if [ "${PackageErrorCode}" == "package_code_0" ] ; then
            NotificationHeaderRestult+="提示：${FullPackageVersionDes}"
        else
            NotificationHeaderRestult+="很抱歉❌：${FullPackageVersionDes}"
        fi
    fi
}

function getLastSendMessage() {
    LastNotificationText="" #初始化
    if [ "${IGNORE_VERSION_HEADER}" != "true" ]; then
        getVersionHeader
        if [ -n "${NotificationHeaderRestult}" ]; then # 当字符串 str1 的长度大于 0（非空）时为真
            LastNotificationText+="${NotificationHeaderRestult}"

            if [ "${NotificationMESSAGETYPE}" == "markdown" ]; then
                LastNotificationText+="\n\n" #为了使得markdown能够换行且空一行
            else
                LastNotificationText+="\n"
            fi
        fi
    fi



    if [ -n "${LongLog}" ]; then # 当字符串 str1 的长度大于 0（非空）时为真
        LastNotificationText+=${LongLog}
    fi

    if [ -n "${PackageErrorMessage}" ] && [ "${PackageErrorMessage}" != "package unknow message" ]; then
        LastNotificationText+="\n${PackageManualInputChangeLog}"
        LastNotificationText+="\n原因:${PackageErrorMessage}"
    fi
}

function send_noti() {
    sendNotiMsg=$1
    #Wechat_CurrentErrorType_ROBOT_URL=$(cat ${Environment_FILE_PATH} | ${JQ_EXEC} -r '.package_notification_argument_current.wechat | select(.name==\"${devBranchName}\")') # -r 去除字符串引号
    ALL_ROBOT_CONFIG=$(cat ${ENVIRONMENT_FILE_PATH} | ${JQ_EXEC} -r '.package_notification_argument_current') # -r 去除字符串引号
    if [ -z "${ALL_ROBOT_CONFIG}" ] || [ "${ALL_ROBOT_CONFIG}" == "null" ]; then
        printf "${RED}❌Error:在 ${YELLOW}${ENVIRONMENT_FILE_PATH} ${RED}中设置发送到企业微信或钉钉的机器人🤖配置信息 ${BLUE}package_notification_argument_current ${RED}不存在，无法发送通知，请检查！${NC}\n"
        exit 1
    fi

    Wechat_ROBOT_URL=$(echo ${ALL_ROBOT_CONFIG} | ${JQ_EXEC} -r '.wechat') # -r 去除字符串引号
    if [ -z "${Wechat_ROBOT_URL}" ]; then
        printf "${RED}❌Error:在 ${YELLOW}${ENVIRONMENT_FILE_PATH} ${RED}中设置发送到企业微信的机器人🤖配置信息 ${BLUE}package_notification_argument_current.wechat ${RED}不存在，无法发送通知，请检查！${NC}\n"
        exit 1
    fi
    Wechat_CurrentErrorType_ROBOT=$(echo ${Wechat_ROBOT_URL} | ${JQ_EXEC} -r --arg LogRobotype "$LogRobotype" '.[$LogRobotype]') # -r 去除字符串引号
    Wechat_CurrentErrorType_ROBOT_URL=$(echo ${Wechat_CurrentErrorType_ROBOT} | ${JQ_EXEC} -r '.value') # -r 去除字符串引号
    Wechat_CurrentErrorType_ROBOT_DES=$(echo ${Wechat_CurrentErrorType_ROBOT} | ${JQ_EXEC} -r '.description') # -r 去除字符串引号
    Wechat_CurrentErrorType_ROBOT_MentionedListJsonStrings=$(echo ${Wechat_CurrentErrorType_ROBOT} | ${JQ_EXEC} -r '.mentioned_list') # -r 去除字符串引号
    printf "${YELLOW}${LogRobotype}错误类型的Wechat_CurrentErrorType_ROBOT=${Wechat_CurrentErrorType_ROBOT_DES}:${Wechat_CurrentErrorType_ROBOT_URL}，需要@的人员为${Wechat_CurrentErrorType_ROBOT_MentionedListJsonStrings}${NC}\n"
    if [ -z "${Wechat_CurrentErrorType_ROBOT_URL}" ]; then
        printf "${RED}❌Error:在 ${YELLOW}${ENVIRONMENT_FILE_PATH} ${RED}中未获取到您的机器人🤖，即在 ${BLUE}package_notification_argument_current.wechat ${RED}里未获取到log类型为 ${YELLOW}${LogRobotype} ${RED}的 ${YELLOW}.value ${RED}值，请检查！${NC}\n"
        exit 1
    fi

    #[shell数组](https://www.runoob.com/linux/linux-shell-array.html)
    declare -a MentionedList
    if [ "${PackageNetworkType}" == "develop1" ] ; then
        MentionedList[0]=""
    elif [ "${PackageNetworkType}" == "develop2" ] ; then
        MentionedList[0]=""
    elif [ "${PackageNetworkType}" == "preproduct" ] ; then
        MentionedList[0]="@all"
    else
        MentionedList[0]="@all"
    fi


    if [ "${verbose}" == true ]; then
        printf "${BLUE}正在执行命令:《 ${YELLOW}sh ${qbase_notification2wechat_path} -robot \"${Wechat_CurrentErrorType_ROBOT_URL}\" -content \"${sendNotiMsg}\" -at \"${Wechat_CurrentErrorType_ROBOT_MentionedListJsonStrings}\" -msgtype \"${NotificationMESSAGETYPE}\" ${NC}》\n"
    fi
    sh ${qbase_notification2wechat_path} -robot "${Wechat_CurrentErrorType_ROBOT_URL}" -content "${sendNotiMsg}" -at "${Wechat_CurrentErrorType_ROBOT_MentionedListJsonStrings}" -msgtype "${NotificationMESSAGETYPE}"
    if [ "${verbose}" == true ]; then
        printf "${BLUE}执行结果:$?${NC}\n"
    fi
}

getLastSendMessage
printf "${LogColor}${LastNotificationText}${NC}\n"
send_noti "${LastNotificationText}"